package concurrencyCookBook;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Two {

	public static void main(String[] args) {
		t3();
		
	}
	public static void t3(){
		D d=new D();
		Thread td=new Thread(d);
		td.start();
		d.setI(1);
	}
	public static void t2(){
		C c=new C();
		Thread tc=new Thread(c);
		Thread tc1=new Thread(c);
		tc.start();
		tc1.start();
	}
	public static void t1(){
		B b=new B();
		Thread t1=new Thread(b);
		Thread t2=new Thread(b);
		t1.start();
		b.t2();
		//t2.start();
	}

}
class D implements Runnable{
	private Integer i;
	private Integer j=0;

	//获取读写锁
	private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
	@Override
	public void run() {
		while(true){
			System.out.println(this.getI());
		}
	}
	public Integer getI() {
		lock.readLock().lock();;
		this.i=j++;
		lock.readLock().unlock();
		return i;
	}
	public void setI(Integer i) {
		
		lock.writeLock().lock();
		try {
			TimeUnit.SECONDS.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.i = i;
		lock.writeLock().unlock();
		
	}
	
}
class C implements Runnable{
	private Lock lock=new ReentrantLock();
	//获取条件
	private Condition condition=lock.newCondition(); 
	@Override
	public void run() {
		try {
			lock.lock();
			TimeUnit.SECONDS.sleep(10);
			System.out.println("gooo");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
		
	}
}
class B implements Runnable{

	@Override
	public void run() {
		System.out.println("start");
		t1();
		System.out.println("finish");
	}
	/**
	 * 把这个对象锁定,如果是2个不同的对象就可以并行执行(b1=new B();b2=new B())
	 * 相当于synchronized(this){}代码块
	 */
	public synchronized void t1(){
		System.out.println("t1 start");
		try {
			TimeUnit.SECONDS.sleep(30);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("t1 end");
	}
	public synchronized void t2(){
		try {
			TimeUnit.SECONDS.sleep(30);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("t2 end");
	}
	
}
